package com.scalar.chiptrack.adaptor.osep;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Iterator;

import java.io.File;


import jxl.Sheet;
import jxl.Workbook;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Feb 21, 2007
 * Time: 1:15:47 PM
 */
public class OSEPFGDataParser extends JobHandler implements AdaptorConstants
{

    HashMap m_fgDataMap         = new HashMap();
    ArrayList fpoTestDisList    = new ArrayList();

    private String filePath = null;
    private Logger m_parserLogger = null;
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    DBTransaction dbTransaction = null;

    /**
     *
     * @throws ScalarException
     */
    public OSEPFGDataParser() throws ScalarException
    {

        String logDirectory;
        String logFileName = "osep_fg_parser%u.log";
        String logPrefix = "Osep_Fg_Parser";
        String level = "debug";
        int maxFileSize = 4096 * 500;
        int fileCount = 1;

        //filePath = ConfigManager.getOSEPFgSheetDirectory();
        logDirectory = new File(filePath).getParent();
        try
        {
            m_parserLogger = new Logger(logDirectory, logFileName, logPrefix, level, maxFileSize, fileCount);
            InventoryLotDAO.setLogger(m_parserLogger);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String args[]) throws Exception
    {
        new OSEPFGDataParser().execute();
    }

    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        printVersionInfo();
        boolean success = true;

        parseOsepFgsheet(filePath);

        try
        {
            // Step 1
            // Save Finished Goods Information
            if (m_fgDataMap.isEmpty() == false)
            {
                log(" Updating Finished Goods Lot Information");
                InventoryLotDAO.saveOsepFgInventoryLot( null, m_fgDataMap.values().iterator() );
            }

        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Finished Goods Lot information into database: " + se);
            throw se;
        }

        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications(VENDOR_NAME_OSEP, true, true, true);

        // Update Adaptor_Run_Info table
        try
        {
            if (success == true)
            {
                //AdaptorRunInfo.saveAdaptorLastUpdatedStatus("OSEP-FG", CONSTANT_SUCCESS);
                System.out.println("SUCCESSFULLY UPDATED IN THE DATABASE");
            }
            /*else
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus("OSEP-FG", CONSTANT_FAILURE);
            }*/

        }
        catch (Exception se)
        {
            success = false;
            log("WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se);
            throw se;
        }

    }//end of execute method


    /**
     *
     * @param fileName
     * @throws Exception
     */
    private void parseOsepFgsheet( String fileName ) throws Exception
    {

        ArrayList sheetList = new ArrayList();
        ArrayList fgList = new ArrayList();
        Sheet sheet = null;

        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );
        try
        {

            File wipStatusFile = new File( fileName );
            if ( wipStatusFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "Parsing the file for OSEP FG Inventory Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "Parsing the file for OSEP FG Inventory Report..." );
			
            Workbook workbook = Workbook.getWorkbook( wipStatusFile );
			
            for ( int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++ )
            {
				sheet = workbook.getSheet( sheetIndex );
				
                if( sheet.getName().trim() != null && ( sheet.getName().endsWith("Inv") || sheet.getName().endsWith("Sheet1") ) )
                {
		            sheetList = parseFgSheet( sheet );

                    segregateFgInfo(sheetList);
                }
            }
        }
        catch ( Exception e )
        {
            throw new ScalarException( "Exception " + e );
        }
    }

    /**
     *
     * @param sheet
     * @return
     * @throws Exception
     */
    private ArrayList parseFgSheet( Sheet  sheet) throws Exception
    {

        OSEPFGWipStatus osepfgWipStatus = null;
        ArrayList fgWipList = new ArrayList();

        try
        {
            Cell[] row = null;
			
            for ( int rowCount = 1; rowCount < sheet.getRows(); rowCount++ )
            {

                row = sheet.getRow( rowCount );
				
                osepfgWipStatus = new OSEPFGWipStatus();
				
                if( row.length > 0 )
                {
                    if ( row[0].getType().equals(CellType.EMPTY) )
                    {
                        osepfgWipStatus.setAssyLoc( null );
                    }
                    else
                    {
                        osepfgWipStatus.setAssyLoc( row[0].getContents().trim() );
                    }

                }
                if( row.length > 1)
                {
                    if ( row[1].getType().equals(CellType.EMPTY) )
                    {
                        osepfgWipStatus.setDevice( null );
                    }
                    else
                    {
                        osepfgWipStatus.setDevice( row[1].getContents().trim() );
                    }
                }
                if( row.length > 2)
                {
                    if ( row[2].getType().equals(CellType.EMPTY) )
                    {
                        osepfgWipStatus.setLot(null );
                    }
                    else
                    {
                        osepfgWipStatus.setLot( row[2].getContents().trim() );
                    }
                }
                if( row.length > 3)
                {
                    if ( row[3].getType().equals(CellType.EMPTY) )
                    {
                        osepfgWipStatus.setSplit(null );
                    }
                    else
                    {
                        osepfgWipStatus.setSplit( row[3].getContents().trim() );
                    }
                }
                if( row.length > 4)
                {
                    if ( row[4].getType().equals(CellType.EMPTY) )
                    {
                        osepfgWipStatus.setActualQtyPulled(null );
                    }
                    else
                    {
                        osepfgWipStatus.setActualQtyPulled( row[4].getContents().trim() );
                    }
                }
                if( row.length > 5)
                {
                    if ( row[5].getType().equals(CellType.EMPTY) )
                    {
                        osepfgWipStatus.setRec_date(null );
                    }
                    else if( row[5].getType().equals( CellType.DATE ))
                    {
                        DateCell dc = (DateCell) row[5];
                        java.util.Date outDate = null;
                        outDate = dc.getDate();
                        if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                        {
                            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
                            cal.setTime(outDate);
                            outDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            osepfgWipStatus.setRec_date(StringUtils.formatDateToString(outDate));
                        }
                        else
                        {
                            Calendar cal = new GregorianCalendar();
                            cal.setTime(outDate);
                            outDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            osepfgWipStatus.setRec_date(StringUtils.formatDateToString(outDate));
                        }
                    }
                }
				
                if ( osepfgWipStatus.getLot() != null && osepfgWipStatus.getLot().trim().length() > 0 
					&& !"lot".equalsIgnoreCase(osepfgWipStatus.getLot().trim()) && !"Total Qty".equalsIgnoreCase(osepfgWipStatus.getLot().trim()) )
                {
                    fgWipList.add( osepfgWipStatus );
                }

            }
        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
            throw ex;
        }

        return fgWipList;
    }

     /**
     *
     * @param wipInfoList
     */
    private void segregateFgInfo( ArrayList wipInfoList )
    {
        InventoryLot inventoryLot = null;
        OSEPFGWipStatus wipStatus = null;

        Iterator iterator = wipInfoList.iterator();

        while ( iterator.hasNext() )
        {
            wipStatus = ( OSEPFGWipStatus ) iterator.next();
            String partNumber = wipStatus.getDevice().trim();
            String lotNumber = wipStatus.getLotNumber().trim();
           
            if( lotNumber != null && partNumber != null )
            {
                inventoryLot = (InventoryLot) m_fgDataMap.get( lotNumber + partNumber );

                if (inventoryLot == null) {
                    inventoryLot = new InventoryLot(VENDOR_NAME_OSEP, LOCATION_TYPE_FG);
                    m_fgDataMap.put( lotNumber + partNumber, inventoryLot);
                }

                int quantity = 0;
                if (inventoryLot.getQtyIn() != null)
                {
                    try {
                        quantity = Integer.parseInt(inventoryLot.getQtyIn());
                    }
                    catch (NumberFormatException npe)
                    {
                    }
                    try {
                        quantity += Integer.parseInt(wipStatus.getActualQtyPulled());
                    }
                    catch (NumberFormatException npe)
                    {
                    }
                }
                else
                {
                    try
                    {
                        quantity = Integer.parseInt(wipStatus.getActualQtyPulled());
                    }
                    catch (NumberFormatException npe)
                    {
                    }
                }

                String assemblyVendor = null;
                if ( "G".equalsIgnoreCase(wipStatus.getAssyLoc()) )
                {
                    assemblyVendor = VENDOR_NAME_CML;
                }
                else if( "L".equalsIgnoreCase(wipStatus.getAssyLoc()))
                {
                     assemblyVendor = VENDOR_NAME_ATK;
                }
                else if( "M".equalsIgnoreCase(wipStatus.getAssyLoc()))
                {
                     assemblyVendor = VENDOR_NAME_ATP;
                }
                else if( "Q".equalsIgnoreCase(wipStatus.getAssyLoc()) || "R".equalsIgnoreCase(wipStatus.getAssyLoc()) || "RA".equalsIgnoreCase(wipStatus.getAssyLoc()) || "SP".equalsIgnoreCase(wipStatus.getAssyLoc()) )
                {
                     assemblyVendor = VENDOR_NAME_CML;
                }
                else if( "T".equalsIgnoreCase(wipStatus.getAssyLoc()))
                {
                     assemblyVendor = VENDOR_NAME_OSET;
                }

                inventoryLot.setLotNumber(lotNumber);
                inventoryLot.setPartNumber(partNumber);
                inventoryLot.setAssemblyVendor(assemblyVendor);
                inventoryLot.setQtyIn(quantity + "");
                inventoryLot.setDateIn(wipStatus.getRec_date());
                inventoryLot.setStatus(LOT_STATUS_RUNNING);
                                         
            }
        }
    }

    /**
     *
     * @param message
     */
    private void log(String message)
    {

        if (message == null) return;

        if (m_parserLogger != null)
        {
            synchronized (m_parserLogger)
            {
                m_parserLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }

    /**
     *
     */
    private void printVersionInfo() {
        String info = "\n\n+----------- Running OSEP FG Data Parser on " + new java.util.Date(System.currentTimeMillis()) + " -------------+\n" +
                "\n+---------------------------------------------------------------+\n" +
                "+                                                                \n" +
                "+           OSEP FG Data Interpreter - Beta          \n" +
                "+                                                                \n" +
                "+    Copy Right (C) 2007 - ScalarSoft Inc., All rights reserved.  \n" +
                "+                                                                \n" +
                "+---------------------------------------------------------------+\n";
        System.out.println(info);
        log(info);
    } //end of printVersionInfo
}
